/**
 * Project: push-center-web-home
 * 
 * File Created at 2014年10月10日
 * 
 * Copyright 2012 Greenline.com Corporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Greenline Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Greenline.com.
 */
package com.greenline.push.home.controllers.apptemplate;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.greenline.guser.annotation.GuserResource;
import com.greenline.push.common.json.BaseJson;
import com.greenline.push.common.json.GridJsonData;
import com.greenline.push.common.utils.StringUtil;
import com.greenline.push.core.pushcenter.DomainAppTemplateManager;
import com.greenline.push.core.pushcenter.AppTemplateManager;
import com.greenline.push.dal.pushcenter.dataobject.AppTemplateDO;
import com.greenline.push.dal.pushcenter.dataobject.DomainAppTemplateDO;
import com.greenline.push.dal.query.AppTemplateQuery;
import com.greenline.push.dal.query.DomainAppTemplateQuery;
import com.greenline.push.services.RefreshConfigService;

/**
 * @Type AppTemplateController
 * @Desc 推送配置
 * @author zhaoli
 * @date 2014年10月10日
 * @Version V1.0
 */
@Controller
@RequestMapping(value = "/apptemplate")
public class AppTemplateController {

    @Resource
    private AppTemplateManager appTemplateManager;
    @Resource
    private DomainAppTemplateManager appDomainTemplateManager;
    @Resource
    private RefreshConfigService refreshService;
    @Resource
    private DomainAppTemplateManager appdomainManager;
    private final Log logger = LogFactory.getLog(AppTemplateController.class);

    @GuserResource("推送配置列表")
    @RequestMapping(value = "/query", method = RequestMethod.GET)
    public String queryRecord(ModelMap model) {
        return "apptemplate/apptemplate_list";
    }

    @GuserResource("推送配置列表")
    @RequestMapping("/query.json")
    @ResponseBody
    public GridJsonData<AppTemplateDO> listRecord(AppTemplateQuery query,
            @RequestParam(value = "page", defaultValue = "1", required = false) String pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "10", required = false) String pageSize) {
        query.setPageIndex(Integer.parseInt(pageIndex));
        query.setPageSize(Integer.parseInt(pageSize));
        GridJsonData<AppTemplateDO> ret = new GridJsonData<AppTemplateDO>();
        appTemplateManager.listByQuery(query);
        List<AppTemplateDO> sDataList = query.getDataList();
        for (AppTemplateDO tmp : sDataList) {
            tmp.setPriority(appdomainManager.getPriorityByApptemplateId(tmp.getId()));
        }
        ret.setQuery(query);
        return ret;
    }
    
    @GuserResource("跳转到模版列表")
    @RequestMapping(value = "/listall-apptemplate", method = RequestMethod.GET)
    public String listallDomain(ModelMap model) {
        return "apptemplate/listall-apptemplate";
    }

    @GuserResource("推送配置添加")
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String addInit(ModelMap model) {
        return "apptemplate/apptemplate_add";
    }

    @GuserResource("推送配置添加")
    @RequestMapping(value = "/add.json", method = RequestMethod.POST)
    public @ResponseBody
    BaseJson add(ModelMap model, @ModelAttribute("template") AppTemplateDO template, Long domainId, Integer priority) {
        BaseJson json = new BaseJson();
        try {
            if (StringUtil.hasEmpty(template.getTemplateId(), template.getAppChannelId(), template.getAppId(), domainId, priority)) {
                json.setHasError(true);
                json.setMessage("提交出错,请检查空值");
                return json;
            }
            Long apptemplateId = appTemplateManager.insert(template);
            // insert app_domain_template
            DomainAppTemplateDO domainapptemplate = new DomainAppTemplateDO();
            domainapptemplate.setAppTemplateId(apptemplateId);
            domainapptemplate.setDomainId(domainId);
            domainapptemplate.setPriority(priority);
            Long appdomainId = appdomainManager.insert(domainapptemplate);

            if (appdomainId > 0) {
                json.setMessage("提交成功！");
            } else {
                json.setHasError(true);
                json.setMessage("提交出错");
            }
        } catch (Exception e) {
            json.setHasError(true);
            json.setMessage("提交出错");
            logger.error(json.getMessage(), e);
        }
        return json;
    }

    @GuserResource("推送配置修改")
    @RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
    public String updateInit(ModelMap model, @PathVariable Long id) {
        AppTemplateDO object = appTemplateManager.getAppTemplateById(id);
        DomainAppTemplateQuery query = new DomainAppTemplateQuery();
        query.setAppTemplateId(id);
        model.put("template", object);
        appdomainManager.listByQuery(query);
        if (query.getDataList() == null || query.getDataList().size() == 0)
            return "apptemplate/apptemplate_update";
        DomainAppTemplateDO appdomainTem = query.getDataList().get(0);
        model.put("domainId", appdomainTem.getDomainId());
        model.put("priority", appdomainTem.getPriority());
        model.put("appDomainTemplateId", appdomainTem.getId());
        return "apptemplate/apptemplate_update";
    }

    @GuserResource("推送配置修改")
    @RequestMapping(value = "/update.json", method = RequestMethod.POST)
    public @ResponseBody
    BaseJson update(ModelMap model, @ModelAttribute("template") AppTemplateDO template, Long appDomainTemplateId, Long domainId,
            Integer priority) {
        BaseJson json = new BaseJson();
        try {
            if (StringUtil.hasEmpty(template.getTemplateId(), template.getAppChannelId(), template.getAppId(), domainId, priority,
                    appDomainTemplateId)) {
                json.setHasError(true);
                json.setMessage("提交出错,请检查空值");
                return json;
            }
            appTemplateManager.update(template);
            DomainAppTemplateDO update = new DomainAppTemplateDO();
            update.setId(appDomainTemplateId);
            update.setDomainId(domainId);
            update.setPriority(priority);
            appdomainManager.update(update);
            
            json.setMessage("提交成功！");
        } catch (Exception e) {
            json.setHasError(true);
            json.setMessage("提交出错");
            logger.error(json.getMessage(), e);
        }
        return json;
    }

    @GuserResource("推送配置删除")
    @RequestMapping(value = "/delete.json", method = RequestMethod.POST)
    public @ResponseBody
    BaseJson delete(ModelMap model, @ModelAttribute("id") Long id) {
        BaseJson json = new BaseJson();
        try {
            if (appTemplateManager.delete(id)) {
                json.setMessage("删除成功！");
            } else {
                json.setHasError(true);
                json.setMessage("删除出错");
            }
        } catch (Exception e) {
            json.setHasError(true);
            json.setMessage("删除出错");
            logger.error(json.getMessage(), e);
        }
        return json;
    }

    @RequestMapping(value = "/refresh.json")
    public @ResponseBody
    BaseJson refresh(ModelMap model) {
        BaseJson json = new BaseJson();
        try {
            if (refreshService.refreshDomainAppTemplateCache()) {
                json.setMessage("提交成功！");
            } else {
                json.setHasError(true);
                json.setMessage("提交出错");
            }
        } catch (Exception e) {
            json.setHasError(true);
            json.setMessage("提交出错");
            logger.error(json.getMessage(), e);
        }
        return json;
    }
}
